<template>
    <main class="flex-center">
        <form @submit.prevent="isAddBook ? addBook($event) : updateBook($event)">
            <message-box :message="message"></message-box>
            <div class="file">
            	图书封面：
                <div class="image">
                    <MyImage :src="image" width="30px"></MyImage>
                </div>
            	<label for="image" class="btn-default">选择图片</label>
            	<input type="file" id="image" name="image" @change="chooseImage"/>
            </div>
            <p>图书名称：<input type="text" name="name" :value="book.name" placeholder="请输入图书名"></p>
            <p>图书作者：<input type="text" name="author" :value="book.author" placeholder="请输入作者名"></p>
            <p>图书单价：<input type="number" name="price" :value="book.price" placeholder="请输入图书单价" min="0" step="0.01"></p>
            <p>图书销量：<input type="number" name="sales" :value="book.sales" placeholder="请输入图书销量" min="0"></p>
            <p>图书库存：<input type="number" name="stock" :value="book.stock" placeholder="请输入图书库存" min="0"></p>
            <p><button class="btn btn-success w-100">{{ $route.meta.title }}</button></p>
        </form>
    </main>
</template>

<script>
    import MessageBox from '../../components/MessageBox.vue';
    import MyImage from '../../components/MyImage.vue';
    import bookService from '../../service/BookService';

    const IMAGE_TYPES = [ 'png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'  ];
    
    /** 
     * 添加或修改图书
     */
    export default {
        components: {
            MessageBox, MyImage
        },
        data() {
            return {
                image: null,
                book: {},
                loadError: false,
                message: '',        // 提示信息
            }
        },  
        computed: {
            /**
             * 是否是添加图书
             */
            isAddBook() {
                return this.$route.name === 'BookAdd';
            },

        },
        methods: {
            /**
             * 图片选择框选择图片实时预览
             */
            chooseImage(event) {
                if (!event.target.files[0]) {
                    return;
                }
                if (this.checkImageType(event.target.files[0])) {
                    this.image = URL.createObjectURL(event.target.files[0]);
                }
            },
            /**
             * 校验文件类型
             */
            checkImageType(file) {
                const extName = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
                if (IMAGE_TYPES.includes(extName)) {
                    this.message = '';
                    return true;
                }
                this.message = `图片仅支持 ${IMAGE_TYPES.join('、')} 类型`;
                return;
            },
            /**
             * 添加图书
             */
            async addBook(event) {
                const result = await bookService.addBook({
                    image: event.target.image.files[0],
                    name: event.target.name.value,
                    author: event.target.author.value,
                    price: event.target.price.value,
                    sales: event.target.sales.value || 0,
                    stock: event.target.stock.value
                });
                if (result.isSuccess) {
                    // 添加成功，跳转到图书管理页面
                    this.$router.push({ name: 'BookManager' });
                } else {
                    this.message = result.message;
                }
            },
            /**
             * 根据图书id获取图书数据
             */
            async getBookById(id) {
                this.book = await bookService.getBookById(id);
                this.image = this.book.imgPath;
            },
            /**
             * 修改图书
             */
            async updateBook(event) {
                const image = event.target.image.files[0];
                // 校验封面图片
                if(image && !this.checkImageType(image)) return;
                const result = await bookService.updateBook({
                    id: this.$route.params.id,
                    image,
                    name: event.target.name.value,
                    author: event.target.author.value,
                    price: event.target.price.value,
                    sales: event.target.sales.value || 0,
                    stock: event.target.stock.value
                });
                if (result.isSuccess) {
                    // 添加成功，跳转到图书管理页面
                    this.$router.push({ name: 'BookManager' });
                } else {
                    this.message = result.message;
                }
            }
        },
        created() {
            if (this.$route.params?.id) {
                this.getBookById(this.$route.params?.id);
            }
        }
    }
</script>